/*
 * UserFormController.java
 *
 * Created on October 9, 2008, 12:08 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.vacuela.publishmx.web.controllers;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindException;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.vacuela.publishmx.constant.Constants;
import org.vacuela.publishmx.context.ServiceContext;
import org.vacuela.publishmx.context.ServiceContextImpl;
import org.vacuela.publishmx.domains.User;
import org.vacuela.publishmx.services.AdminService;
import org.vacuela.publishmx.util.PublishUtil;
import org.vacuela.publishmx.web.bean.UserForm;

/**
 *
 * @author nestor.carrasco
 */
public class UserFormController extends SimpleFormController {
    
    AdminService adminSvc;
    
    /** Creates a new instance of UserFormController */
    public UserFormController() {
        setSessionForm(true);
        setValidateOnBinding(false);
        setCommandName("userForm");
        setFormView("user/userManagement");
    }
    
    public void setAdminService(AdminService svc){
        adminSvc = svc;
    }
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        String userId = PublishUtil.checkNull(request.getParameter("userAction"),"");
        if ( "".equals(userId)){
            return new UserForm();
        }
        else {
             ServiceContext context = new ServiceContextImpl();
             context.setAttribute("userId",new Integer(userId));
             this.adminSvc.getUserById(context);
             User userDomain = (User)context.getAttribute("userDomain");
            return new UserForm (userDomain);
        }
        /*
                UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
                if (userSession != null) {
                        return new AccountForm(this.petStore.getAccount(userSession.getAccount().getUsername()));
                }
                else {
                        return new AccountForm();
                }
         */
        
    }
    
    protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
			throws Exception {

		UserForm userForm = (UserForm) command;
		User user = userForm.getUser();
		
		errors.setNestedPath("user");
		getValidator().validate(user, errors);
		errors.setNestedPath("");

		if (userForm.isNewUser()) {
			//account.setStatus("OK");
			ValidationUtils.rejectIfEmpty(errors, "user.userId", "USER_ID_REQUIRED", "User ID is required.");
			if (user.getPassword() == null || user.getPassword().length() < 1 ||
					!user.getPassword().equals(userForm.getRepeatedPassword())) {
			 errors.reject("PASSWORD_MISMATCH",
					 "Passwords did not match or were not provided. Matching passwords are required.");
			}
		}
		else if (user.getPassword() != null && user.getPassword().length() > 0) {
		  if (!user.getPassword().equals(userForm.getRepeatedPassword())) {
				errors.reject("PASSWORD_MISMATCH",
						"Passwords did not match. Matching passwords are required.");
		  }
	  }
 	}
    
    
    protected Map referenceData(HttpServletRequest request) throws Exception {
        Map model = new HashMap();
        ServiceContext context = new ServiceContextImpl();
        adminSvc.getUserList(context);
        List<User> userList = (List<User>)context.getAttribute("userList");
        model.put("roles", Constants.ROLES);
        model.put("usersList",userList);
        return model;
    }
    
    protected ModelAndView onSubmit(
            HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
            throws Exception {
    /*    
        AccountForm accountForm = (AccountForm) command;
        try {
            if (accountForm.isNewAccount()) {
                this.petStore.insertAccount(accountForm.getAccount());
            } else {
                this.petStore.updateAccount(accountForm.getAccount());
            }
        } catch (DataIntegrityViolationException ex) {
            errors.rejectValue("account.username", "USER_ID_ALREADY_EXISTS",
                    "User ID already exists: choose a different ID.");
            return showForm(request, response, errors);
        }
        
        UserSession userSession = new UserSession(this.petStore.getAccount(accountForm.getAccount().getUsername()));
        PagedListHolder myList = new PagedListHolder(
                this.petStore.getProductListByCategory(accountForm.getAccount().getFavouriteCategoryId()));
        myList.setPageSize(4);
        userSession.setMyList(myList);
        request.getSession().setAttribute("userSession", userSession);
     */
        UserForm userForm = (UserForm)command;
        ServiceContext context = new ServiceContextImpl();
        context.setAttribute("userDomain", userForm.getUser());
        try {           
                adminSvc.saveUpdateUser(context);            
        } catch (DataIntegrityViolationException ex) {
            errors.rejectValue("user.userId", "USER_ID_ALREADY_EXISTS",
                    "User ID already exists: choose a different ID.");
            return showForm(request, response, errors);
        }
        return super.onSubmit(request, response, command, errors);
    }
    
}
